import { Op } from 'sequelize';
import { StatusModel, DateRecord } from '../../until/context';
import DataModel from '../../model/data';
import Tool from '../../until/tool';
import { fn, col, literal } from 'sequelize';
class AnalyService { 
        // 获取分析报告
    async getAnayleRecord(startTime: string, endTime: string, module_id: number, module_type: string, selectDate: string, gateway_ip: string) {
        try {
            // 验证module_type是否为有效的字段
            const validTypes = ['tem', 'hum', 'pre', 'inf', 'uvc'];
            if (!validTypes.includes(module_type)) {
                throw new Error(`无效的模块类型: ${module_type}，支持的类型: ${validTypes.join(', ')}`);
            }

            // 使用ORM查询数据
            const data = await DataModel.findAll({
                attributes: [
                    module_type,
                    [fn('strftime', '%Y-%m-%d %H:%M:%S', col('createdAt'), 'localtime'), 'timer'],
                    'time',
                    'gateway_ip',
                    'module_id'
                ],
                where: {
                    module_id: module_id,
                    gateway_ip: gateway_ip,
                    date: selectDate,
                    [Op.and]: [
                        literal(`strftime('%Y-%m-%d %H:%M:%S', createdAt, 'localtime') > '${startTime}'`),
                        literal(`strftime('%Y-%m-%d %H:%M:%S', createdAt, 'localtime') < '${endTime}'`)
                    ]
                },
                order: [['createdAt', 'ASC']],
                raw: true
            });

            return {
                success: true,
                data: data,
                total: data.length,
                module_id: module_id,
                module_type: module_type,
                date_range: {
                    start_time: startTime,
                    end_time: endTime,
                    select_date: selectDate
                }
            };
        } catch (error) {
            console.error('获取分析记录失败:', error);
            throw error;
        }
    }

    // 获取完整的传感器数据分析报告
    async getCompleteAnalyRecord(startTime: string, endTime: string, module_id: number, selectDate: string) {
        try {
            // 使用ORM查询完整的传感器数据
            const data = await DataModel.findAll({
                attributes: [
                    'tem',
                    'hum', 
                    'pre',
                    'inf',
                    'uvc',
                    [fn('strftime', '%Y-%m-%d %H:%M:%S', col('createdAt'), 'localtime'), 'timer'],
                    'time',
                    'gateway_ip',
                    'module_id',
                    'info'
                ],
                where: {
                    module_id: module_id,
                    date: selectDate,
                    [Op.and]: [
                        literal(`strftime('%Y-%m-%d %H:%M:%S', createdAt, 'localtime') > '${startTime}'`),
                        literal(`strftime('%Y-%m-%d %H:%M:%S', createdAt, 'localtime') < '${endTime}'`)
                    ]
                },
                order: [['createdAt', 'ASC']],
                raw: true
            });
            
            return {
                success: true,
                data: data,
                total: data.length,
                module_id: module_id,
                sensor_types: ['tem', 'hum', 'pre', 'inf', 'uvc'],
                date_range: {
                    start_time: startTime,
                    end_time: endTime,
                    select_date: selectDate
                },
                description: {
                    tem: '温度数据',
                    hum: '湿度数据', 
                    pre: '压力数据',
                    inf: '红外数据',
                    uvc: '紫外数据',
                    timer: '数据记录时间',
                    time: '数据采集时间',
                    gateway_ip: '网关IP地址',
                    module_id: '模块ID',
                    info: '原始数据信息'
                }
            };
        } catch (error) {
            console.error('获取完整分析记录失败:', error);
            throw error;
        }
    }

     async getHistryList(module_id,type) {
        let date = Tool.getCurrentDate()
        let count = await DateRecord.findAll({
            where: {
                [Op.not]: {
                    currentDate: date
                }
            },
            limit: 4
        })
        let dateList = count.map(item => item.dataValues.currentDate)
        let errNum = []
        for(let i=0;i<dateList.length;i++) {
           let num:any = await StatusModel.count({
                where: {
                    module_id,
                    date: dateList[i],
                    [type]: 1
                }
            })
            //@ts-ignore
            errNum.push(num)
        }
        return {
            dateList,
            errNum
        }
    }

    async getHistoryDataByType(gateway_ip: string, module_id: string, type: string, pageSize: number, page: number) {
        try {
            const offset = (page - 1) * pageSize;
            
            // 验证type参数是否为有效的数据类型
            const validTypes = ['uvc', 'inf', 'tem', 'hum', 'pre'];
            if (!validTypes.includes(type)) {
                throw new Error(`无效的数据类型: ${type}，支持的类型: ${validTypes.join(', ')}`);
            }

            // 使用ORM查询指定类型的历史数据
            const { count, rows } = await DataModel.findAndCountAll({
                attributes: [
                    type,
                    [fn('strftime', '%Y-%m-%d %H:%M:%S', col('createdAt'), 'localtime'), 'timer'],
                    'time',
                    'gateway_ip',
                    'module_id',
                    'date'
                ],
                where: {
                    gateway_ip: gateway_ip,
                    module_id: parseInt(module_id),
                    [type]: {
                        [Op.and]: [
                            { [Op.ne]: null },
                            { [Op.ne]: '' }
                        ]
                    }
                },
                order: [['createdAt', 'DESC']],
                limit: pageSize,
                offset: offset,
                raw: true
            });

            return {
                data: rows,
                total: count,
                pageSize,
                currentPage: page,
                totalPages: Math.ceil(count / pageSize),
                gateway_ip,
                module_id,
                dataType: type
            };
        } catch (error) {
            console.error('获取历史数据失败:', error);
            throw error;
        }
    }
}

export default new AnalyService();